// pages/product_detail/product_detail.js
var city = require("../../utils/citys");
 const  citys = city.city_data
//  console.log(citys);
// console.log(citys.city_data);
Page({
  /**
   * 
   * 页面的初始数据
   */
  data: {
    show_data:[],
    search_result_data:[],
    count:1,

    //控制模态框
    hidden:false,
    request_count:0,
    //控制地址展开栏
    flag:false,
    //地址数据
     all_address:"",
    //地址
    address: null,
    //立即购买时的 address_id
    address_id:null,
    //地址的index
    index:0,
    //评论6个类型 对象
    comment_obj:{},
    //购物车商品总个数
    purchase_sum:0,
    //商品价格
    price:null,
    //sku下标
    idx:0,
    //sku key
    price_arr:[],
    //sku key
    arr_key:[],
    //阴影层控制
    height: 0,
    //个数层控制
    hegiht1: "0vh",
    //商品个数
    product_count: 1,
    //商品总价
    sum_price: 0,
    //1 是促销商品数据 2是商品列表数据
    state: "",
    //商品id
    id: null,
    //skucolor
    color:"",
    //sku  edition
    edition:"",
    //sku信息
    sku: "",
    product_detail_data: {
      // create_time: 1600932028,
      // good_id: 910,
      // hot: 1,
      // id: 349,
      // pic: "http://api_dev.wanxikeji.cn/app/pic/20200924/20200924072026734.jpg",
      // promotion_id: 335,
      // promotion_price: "200.00",
      // status: 1,
      // title: "Dior迪奥口红999哑光520正品740经典正红888限量版送礼套装礼盒装",
      // update_time: 1600932028,
      // vice_title: "经典款式"
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     console.log( wx.getStorageSync('token')),
    //处理数组 edition  
    this.setData({
      state: options.state
    })
    if (this.data.state == 1) {
      this.setData({
        id: options.good_id
      })
      this.setData({
        sum_price: this.data.product_detail_data.promotion_price
      })
      this.product_detail_cuxiao()
    } else if (this.data.state == 2) {
      this.setData({
        product_detail_data: JSON.parse(options.item)
      })
      this.setData({
        sum_price: this.data.product_detail_data.price
      })
      console.log(this.data.product_detail_data);
    } else if (this.data.state == 3) {
      console.log(options.good_id);
      this.setData({
        id: options.good_id
      })
      wx.request({
        url: "http://api_devs.wanxikeji.cn//api/goodInfo",
        method: "POST",
        data: {
          "good_id": this.data.id
        },
        success:(res)=>{
        this.control_hidden();

          this.setData({
          product_detail_data: res.data.data,
          })
          this.setData({
          sum_price: this.data.product_detail_data.price
          })

    console.log(this.data.product_detail_data);

          //如果传入的sku合法 分离edition键值对
          if(JSON.parse(JSON.parse(this.data.product_detail_data.info[0].edition)).length !=0){
            this.setData({
            edition: JSON.parse(JSON.parse(this.data.product_detail_data.info[0].edition))
            })
            console.log(this.data.edition);
            let arr_key =[];
            let price_arr = [];
            // let arr = [{颜色: "红色", 价格: "5000",大小:"mini"},{颜色: "绿色", 价格: "6000"}]
            for(let i =0 ;i < this.data.edition.length;i++ ){
              let arr1 = Object.keys( this.data.edition[i]);
              let arr2 = Object.values( this.data.edition[i]);
              arr_key.push(arr2)
              for(let k = 0; k < arr1.length; k++){
                if(arr1[k] =="价格"){
                  let price =  this.data.edition[i][arr1[k]];
                  price_arr.push(price)
                }
              }
            }
            this.setData({
              arr_key:arr_key,
              price_arr:price_arr
            })
            this.setData({
              price:this.data.price_arr[0]
            })
           this.setData({
            sum_price:this.data.price_arr[0]
           })
         }
        }
      })
    }
    //请求地址
    this.address();
    //请求购物车商品个数
    this.purchase_count_sum()
    //请求评论
    this.getcomment()
    this.product_show_list()
    // wx.request({
    //   url: 'http://api_devs.wanxikeji.cn/api/orderList',
    //   method:'post',
    //   data:{
    //     'token':'6ede24c10dfd4900dd719b852bbacb1f'
    //   },
    //   success:(res)=>{
    //     this.control_hidden();
    //     // console.log(res);
    //   }
    // })
  },
  //新增收获地址
  add_receive_address(){
    wx.navigateTo({
      url: '../userSet/addAddress/addAddress',
    })
  },
  address_show_close(){
    this.setData({
      flag:false
    })
  },
//控制模态框
  control_hidden(){
    this.setData({
     request_count:this.data.request_count + 1,
    })
    console.log(this.data.request_count);
    if(this.data.request_count == 4 && (this.data.state == 1||this.data.state ==3)){
      this.setData({
        hidden:false   
      })
    }
    if(this.data.request_count == 3 && this.data.state == 2){
      this.setData({
        hidden:false
      })
    }
   } ,
 //控制显示
  address_show_control(){
    this.setData({
      flag:true
    })
  },
  select_option(e){
    // let index = e.currentTarget.dataset.index;
    this.setData({
      index:e.currentTarget.dataset.index,
    })
    this.setData({
      address_id:this.data.address[this.data.index].address_id
    })
    this.setData({
      flag:false
    })
    console.log(this.data.address_id);
  },
  //请求购物车商品的个数  进入详情页显示购物车商品个数  加入购物车显示购物车商品个数
  purchase_count_sum(){
        wx.request({
          url: 'http://api_devs.wanxikeji.cn//api/shoppingCarList',
          method: "POST",
          data:{
          "token": wx.getStorageSync('token'),
          },
          success:(res)=>{
            // console.log(res.data.data);
            this.setData({
              purchase_sum:res.data.data.count
            })
          }
        })
  },
 //选择sku选项
  seceleted(e){
    let index = e.currentTarget.dataset.index;
     this.setData({
       idx:index
     })
    this.setData({
      price:this.data.price_arr[index]
    })
    if (this.data.state == 3) {
      //sku是正确格式
      if(this.data.price_arr.length !=0 && this.data.arr_key.length !=0){
        this.setData({
          sum_price: parseInt(this.data.product_count) * parseFloat(this.data.price)
        })
      }
      //不是正确格式
      else{
      this.setData({
        sum_price: parseInt(this.data.product_count) * parseFloat(this.data.product_detail_data.price)
      })
    }
  }
  },

  initPage() {
    this.data.count++;
    let arr =[]
    for(let i = 0 ;i < this.data.search_result_data.length &&i<this.data.count*6 ;i++){
     arr.push(this.data.search_result_data[i])
    }
    console.log(arr);
    this.setData({
      show_data:arr
    })
     console.log(this.data.show_data);
  },
   //加载更多
   loading_more(){
    this.data.count++;
    this.setData({
      count:this.data.count
    })
    this.initPage()
    console.log(this.data.count);
  },
  //商品列表处理
  enter_product_detail(e){
    console.log(123);
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({url:"../product_detail/product_detail?good_id="+item.good_id +"&state=3"});

  },
 
     //商品列表显示
     product_show_list(){
      console.log(123);
      wx.request({
          url: 'http://api_devs.wanxikeji.cn//api/homeGoodList',
          method: "POST",
          data: {
            "token":wx.getStorageSync('token')
          },
          success:(res)=>{
            // console.log(res.data.data);
            this.setData({
              search_result_data:res.data.data
            })
            this.initPage();
            console.log(this.data.show_data.length);
            this.control_hidden()

          }
         })
    },

  //加入购物车
  add_purchase_car(){
     let token = wx.getStorageSync('token');
     //未登录
    if(token ==""){
      wx.showToast({
        title: '还没有登录额',
        icon: 'error',
        duration: 2000,//持续的时间
        success: (res) => {
          setTimeout(() => {
            if (wx.getStorageSync('token') == '') {
              wx.switchTab({
                url: '../usercenter/usercenter',
              })
            }
          },2000)
        }
      })
    }
    //已登录
    else{
      let good_id;
      let price;
      let sku;
      //分good_id price 如果sku是正确格式，则价格是sku里默认的第一个
      if(this.data.state ==1 ||this.data.state==3){
        good_id = this.data.id;
        console.log(good_id);
        if(this.data.state ==1){
          price = this.data.product_detail_data.promotion[0].promotion_price;
          sku = JSON.stringify([])
        }
        if(this.data.state ==3){
          price = this.data.price;
          sku = JSON.stringify(this.data.arr_key[this.data.idx])
        }
      }
      if(this.data.state ==2 ){
       good_id = this.data.product_detail_data.good_id;
       price = this.data.product_detail_data.price;
       sku = JSON.stringify([])
      }
      wx.request({
        url: 'http://api_devs.wanxikeji.cn//api/shoppingCarAddModify',
        method: "POST",
        data: {
          "token": wx.getStorageSync('token'),
          "good_id":good_id,
          "num":this.data.product_count,
          "price":price,
          "money":this.data.sum_price,
          "sku":sku
        },
        success: () => {
          wx.showToast({
            title: '已加入购物车',
            icon: 'success',
            duration: 1500//持续的时间
          })
        this.purchase_count_sum()
        }
      })
    }
  },
  //商品跳转页面
  change_path() {
      wx.navigateBack({
        delta: 1
      })
  },
  // 跳转商品搜索页
  go_search() {
    wx.navigateTo({
      url: '../search/search',
    })
  },

  //获取促销商品详情
  product_detail_cuxiao() {
    wx.request({
      url: 'http://api_devs.wanxikeji.cn//api/promotionGoodInfo',
      method: "POST",
      data: {
        "good_id": this.data.id
      },
      success: (res) => {
        this.setData({
          product_detail_data: res.data.data
        })
        console.log(this.data.product_detail_data);

        this.setData({
          edition:JSON.parse(this.data.product_detail_data.info[0].edition)
        })
        console.log(this.data.edition);
        this.setData({
          sum_price: this.data.product_detail_data.price
        })
        this.control_hidden();
        // let return_addree = res.data.data;
      },
    })
  },
  //地址显示
  address() {
    console.log(123);
     let token = wx.getStorageSync('token');
    // let token = "093a9b3d963e0d8042130b2d0c0430e1"
    //如果登录,请求地址 
    if (token != "") {
      wx.request({
        url: 'http://api_devs.wanxikeji.cn//api/userAddressList',
        method: "POST",
        data: {
          "token": token
        },
        success: (res) => {
          let return_addree = res.data.data;
          console.log(res);
          console.log("地址列表");
          // console.log(return_address);
          //未添加地址
          if (return_addree.length == 0) {
            this.setData({
              address: "no"
            })
          }
          //数据库有地址 请求地址列表
          else {
            wx.request({
              url: 'http://api_devs.wanxikeji.cn//api/userAddressList',
              method: "POST",
              data: {
              "token": token
              },
              success:(res)=>{
                console.log( res);
                this.setData({
                  all_address:res.data.data
                })
                // this.data.all_address;
                console.log(citys);
                this.covert_address();
                this.control_hidden();
              }
            })
          }
        },
      })
    }
    //未登录
    else {
      this.setData({
        address: "未登录"
      })
    }
  },
  //处理地址编码
  covert_address(){
    let  arr =[]
    let  obj ={}
    for(let i = 0; i < this.data.all_address.length;i++){
      // console.log("/n");
    for(let j =0 ;j < citys.length;j++ ){
      if(citys[j].code == this.data.all_address[i].procince){
        console.log(citys[j].name);
        obj.address_id = this.data.all_address[i].address_id
        obj.province = citys[j].name;
        for(let k = 0 ;k < citys[j].sub.length; k++){
          // console.log(k);
          if(citys[j].sub[k].code ==this.data.all_address[i].city){
            console.log(citys[j].sub[k].name);
             obj.city = citys[j].sub[k].name;
            for(let s = 0 ;s < citys[j].sub[k].sub.length;s++){
              if(citys[j].sub[k].sub[s].code == this.data.all_address[i].area){
                // console.log(citys[j].sub[k].sub[s].name);
                obj.area = citys[j].sub[k].sub[s].name
              }
            }
          }
        }
      }
    }
    let address = obj.province + obj.city + obj.area + this.data.all_address[i].detailed;
    let temp ={};
    temp.address = address;
    temp.address_id = obj.address_id;
    arr.push(temp)
  }
  this.setData({
    address:arr
  })
  console.log(arr);
  },

  // 立即购买 生成订单
  form_order_now(){
    let token = wx.getStorageSync('token');
     //未登录
    if(token ==""){
      wx.showToast({
        title: '还没有登录额',
        icon: 'error',
        duration: 2000, //持续的时间
        success: (res) => {
          setTimeout(() => {
            if (wx.getStorageSync('token') == '') {
              wx.switchTab({
                url: '../usercenter/usercenter',
              })
            }
          },2000)
        }
      })
    }
    else{
      let obj_params = {};
      obj_params.img = this.data.product_detail_data.img;
      console.log( this.data.product_detail_data.img);
      obj_params.good_name = this.data.product_detail_data.good_name;
      console.log( this.data.product_detail_data.good_name);

      obj_params.price= this.data.product_detail_data.price;
      console.log( this.data.product_detail_data.price);

      let arr = [];
      arr.push(obj_params);
      console.log(arr);

      let address_id = this.data.address[this.data.index].address_id;
      let money = this.data.sum_price;
      let shopping_cars_ids = JSON.stringify(arr)

      wx.navigateTo({
        url: '../order/order?address_id=' + address_id + "&shopping_cars_ids=" + shopping_cars_ids + "&money=" + money
      })
  }
  },
 //点击购物车进入购物车
 enter_purchase_car(){
  wx.switchTab({
    url: '../gouwuche/gouwuche',
  })
 },
  //获取评价
  getcomment(){
    wx.request({
      url: 'http://api_devs.wanxikeji.cn//api/commentList',
      method: "POST",
      data: {
      "good_id":this.data.product_detail_data.good_id||this.data.id,
      "tag_id": "1"
      },
      success:(res)=>{
      console.log(res);
      this.setData({
        comment_obj:res.data.data.comment
      })
      this.control_hidden();

      // console.log(this.data.comment_obj);
      }
    })
  },
  //获取某个具体tag_id下面的评论
  getcomment_list(e){
    console.log(e);
      let tag_id = e.currentTarget.dataset.tag_id;
      let good_id = e.currentTarget.dataset.good_id;
      console.log(good_id);
      console.log(tag_id,good_id);
  },
  //没有地址跳转个人中心添加地址
  addaddress() {
    // console.log(123);
    wx.switchTab({
      url: '../usercenter/usercenter'
    })
  },
  //未登录跳转登录页
  login() {
    wx.switchTab({
      url: '../usercenter/usercenter'
    })
  },

  //展开按钮
  product_expand() {
    this.setData({
      height: 450,
      height1: "100vh"
    })
  },
  close() {
    this.setData({
      height: 0,
      height1: "0"
    })
  },
  //商品个数控制
  reduce_count() {
    this.setData({
      product_count: this.data.product_count - 1,
    })

    if (this.data.product_count < 1) {
      this.setData({
        product_count: 1,
      })
    }
    if (this.data.state == 1) {
      this.setData({
        sum_price: parseInt(this.data.product_count) * parseFloat(this.data.product_detail_data.promotion[0].promotion_price)
      })
    }
    if (this.data.state == 2) {
      this.setData({
        sum_price: parseInt(this.data.product_count) * parseFloat(this.data.product_detail_data.price)
      })
    }
    if (this.data.state == 3) {
      if(this.data.price_arr.length !=0 &&this.data.arr_key.length !=0){
        this.setData({
          sum_price: parseInt(this.data.product_count) * parseFloat(this.data.price)
        })
      }
      else{
      this.setData({
        sum_price: parseInt(this.data.product_count) * parseFloat(this.data.product_detail_data.price)
      })
    }
  }

  },
  add_count() {
    this.setData({
      product_count: this.data.product_count + 1,
    })
    // console.log(this.data.product_detail_data.promotion[0].pro);

    if (this.data.state == 1) {
      this.setData({
        sum_price: parseInt(this.data.product_count) * parseFloat(this.data.product_detail_data.promotion[0].promotion_price)
      })
    }
    if (this.data.state == 2) {
      this.setData({
        sum_price: parseInt(this.data.product_count) * parseFloat(this.data.product_detail_data.price)
      })
    }
    if (this.data.state == 3) {
      if(this.data.arr_key.length !=0  &&this.data.price_arr.length !=0){
        this.setData({
        sum_price: parseInt(this.data.product_count) * parseFloat(this.data.price)
        })
      }
      else{
        this.setData({
          sum_price: parseInt(this.data.product_count) * parseFloat(this.data.product_detail_data.price)
        })
      }
     
    }
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // if (wx.getStorageSync('token') == '') {
    //   wx.switchTab({
    //     url: '../usercenter/usercenter',
    //   })
    //   wx.showToast({
    //     title: '请登录',
    //     icon: 'error'
    //   });
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.initPage();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})